package com.uxsino.simo.indicator.retractor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.uxsino.simo.networkentity.EntityInfo;
import com.uxsino.simo.query.QueryTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.uxsino.commons.utils.config.ConfigProp;
import com.uxsino.simo.query.QueryContext;

/**
 * 
 *example input:
OK - Listed applications for virtual host localhost
/:running:0:ROOT
/examples:running:0:examples
/host-manager:running:0:host-manager
/manager:running:0:manager
/docs:running:0:docs
 * 
 * <retract indicator="abcd" parser="line_list" skip_row="1" col_delimiter="" row_delimiter="">
 *    <column col_id="1" field="context_path" parser="regex" pattern=""/>
 *  </retract>
 * 
 */
public class LineListRetractor extends ListValueRetractor {
    private static Logger logger = LoggerFactory.getLogger(LineListRetractor.class);

    @ConfigProp(name = "skip_row")
    public String skipRow;

    @ConfigProp(name = "col_delimiter")
    public String colDelimiter;

    @ConfigProp(name = "row_delimiter")
    public String rowDelimiter;

    public LineListRetractor() {
        super();
        colDelimiter = ":";
        skipRow = "1";
        rowDelimiter = "((\\n\\r)|(\\r\\n)){1}|(\\r){1}|(\\n){1}";
    }

    @Override
    public Object doRetract(EntityInfo entity, QueryContext ctxt, QueryTemplate qt, Object obj) {
        // System.out.println("skip row: " + skipRow + " col_del: " + colDelimiter + " row_del: " + rowDelimiter);
        List<Map<String, Object>> result = new ArrayList<>();
        if (obj == null) {
            logger.error("retract object is null");
            return null;
        }
        String[] lines = ((String) obj).split(rowDelimiter);
        int start = 1;
        try {
            start = Integer.parseInt(skipRow);
        } catch (NumberFormatException e) {
            logger.error(e.getMessage());
        }
        for (int i = start; i < lines.length; i++) {
            String[] arr = lines[i].split(colDelimiter);
            Map<String, Object> innerMap = new HashMap<>();

            for (ColumnEntry entry : columnEntries) {
                int col_num = -1;
                try {
                    col_num = Integer.parseInt(entry.index);
                } catch (NumberFormatException e) {
                    logger.error("column index format error: {}", entry.index);
                    continue;
                }
                if (col_num < 1 || col_num > arr.length) {
                    logger.error("column index out of range: {}", col_num);
                    continue;
                }
                innerMap.put(entry.field.getName(), entry.retractor.retract(entity, ctxt, qt, arr[col_num - 1]));
            }
            result.add(innerMap);
        }
        return result;
    }

}
